package problems;

import java.math.BigInteger;

public class Euler039Threaded extends AbstractThreadedEuler {

	int maxNumSolutions = 1;
	long maxNumSolutionsFor = 3 + 4 + 5; //the golden cut is the lower bound - there can be only one solution here

	
	@Override
	protected long getStartValue() {
		return 2 + maxNumSolutionsFor;
	}

	@Override
	protected void doCalculation(long forValue) {
		int foundSolutions = 0;
		for (long c = forValue; c >= forValue / 3; c--) {
			for (long b = forValue - c; b >= (forValue - c) / 2; b--) {
				long a = forValue - (b + c);
				if (a == 0 || b == 0 || c == 0) continue;
				if (doesPythagorasHold(a, b, c)) {
					foundSolutions++;
				}
			}
		}
		if (foundSolutions > maxNumSolutions) {
//			System.out.println(i + " has " + foundSolutions + " solutions");
			maxNumSolutions = foundSolutions;
			maxNumSolutionsFor = forValue;
		}
	}

	@Override
	protected Number getFinalAnswer() {
		return maxNumSolutionsFor;
	}

	@Override
	protected boolean continueCalculating() {
		return this.counter <= 1000;
	}

	@Override
	protected Number getCorrectAnswer() {
		return 840L;
	}
	
	private boolean doesPythagorasHold(long a, long b, long c) {
		if (a <= 0 || b <= 0 || c <= 0) throw new UnsupportedOperationException("only positive values");
		return BigInteger.valueOf(a).pow(2).add(BigInteger.valueOf(b).pow(2)).equals(BigInteger.valueOf(c).pow(2));
	}

}
